// 
//  Copyright 2011  comphilip
// 
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
// 
//        http://www.apache.org/licenses/LICENSE-2.0
// 
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;

namespace Dict4Engkoo.Engkoo {
	internal class Sentences {
		private static Regex _clientRegex = new Regex(@"\{\d+\#|\$\d+\}|\{\#{1,2}\*|\*\${1,2}\}", 
		                                              RegexOptions.Compiled | RegexOptions.IgnoreCase);
		
		private JToken _senToken;
		
		public Sentences(JToken SenToken) {
			_senToken = SenToken;
		}
		
		public IEnumerable<KeyValuePair<string, string>> GetSentences(){
			JArray array = _senToken as JArray;
			if (array != null)
				foreach(var item in array)
					yield return GetSentence(item);
			else
				yield return GetSentence(_senToken);
		}
		
		private static KeyValuePair<string, string> GetSentence(JToken SenToken){
			string key = string.Empty, value = string.Empty;
			JToken cn = SenToken["CN"];
			if (cn != null){
				JToken d = cn["D"];
				if (d != null){
					JToken sentence = d["$"];
					if (sentence != null)
						key = CleanSentence(sentence.Value<string>());
				}
			}
			
			JToken en = SenToken["EN"];
			if (en != null){
				JToken d = en["D"];
				if (d != null){
					JToken sentence = d["$"];
					if (sentence != null)
						value= CleanSentence(sentence.Value<string>());
				}
			}
			
			return new KeyValuePair<string, string>(Uri.UnescapeDataString(key), Uri.UnescapeDataString(value));
		}
		
		private static string CleanSentence(string RawSentence){
			return _clientRegex.Replace(RawSentence, string.Empty);
		}
	}
}

